<template>
  <div class="location-container">
    <!-- 位置获取区域 -->
    <div class="location-section">
      <div class="tracking-controls">
        <button 
          @click="isTracking ? stopTracking() : startTracking()" 
          class="tracking-button"
          :class="{ active: isTracking }"
        >
          <i class="fas" :class="isTracking ? 'fa-stop-circle' : 'fa-play-circle'"></i>
          {{ isTracking ? '停止追踪' : '开始追踪' }}
        </button>
        
        <div v-if="isTracking" class="tracking-status">
          <i class="fas fa-sync-alt"></i>
          <span>每20秒更新一次位置</span>
        </div>
      </div>

      <div class="location-type-selector">
        <label>位置类型：</label>
        <select v-model="selectedLocationType" class="location-type-dropdown">
          <option v-for="type in locationTypes" :key="type.value" :value="type.value">
            {{ type.label }}
          </option>
        </select>
      </div>

      <button @click="fetchAndShowLocation" class="location-button" :disabled="isLocating">
        <i class="fas" :class="isLocating ? 'fa-spinner fa-pulse' : 'fa-location-arrow'"></i>
        {{ isLocating ? '定位中...' : '获取我的位置' }}
      </button>

      <div v-if="locationError" class="location-error">
        <i class="fas fa-exclamation-triangle"></i> {{ locationError }}
      </div>

      <div v-if="currentLocation.address" class="location-info">
        <p><i class="fas fa-map-marker-alt"></i> {{ currentLocation.address }}</p>
        <p v-if="currentLocation.coords.accuracy">
          <i class="fas fa-bullseye"></i> 定位精度: ±{{ currentLocation.coords.accuracy.toFixed(1) }}米
        </p>
        <p v-if="selectedLocationType">
          <i class="fas fa-tag"></i> 位置类型: {{ getLocationTypeLabel(selectedLocationType) }}
        </p>
      </div>
    </div>

    <!-- 百度地图显示位置 -->
    <div class="map-section">
      <h3 class="section-title">当前位置</h3>
      <BaiduMap :initial-location="initialLocation" :auto-locate="false" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import BaiduMap from '@/components/BaiduMap.vue'
import { updateUserTrack } from '@/api/map' // 导入API方法
// 位置类型定义
const locationTypes = [
  { value: 'home', label: '家' },
  { value: 'work', label: '工作地点' },
  { value: 'leisure', label: '休闲场所' },
  { value: 'transport', label: '交通枢纽' },
  { value: 'shopping', label: '购物中心' },
  { value: 'other', label: '其他' }
]

const initialLocation = ref<{ lng: number; lat: number } | null>(null)
const isLocating = ref(false)
const isTracking = ref(false)
const locationError = ref('')
const locationTimer = ref<number | null>(null)
const trackingInterval = 20000 // 20秒间隔
const selectedLocationType = ref('other') // 默认选择"其他"

const currentLocation = ref({
  coords: {
    latitude: 0,
    longitude: 0,
    accuracy: 0
  },
  address: '',
  type: 'other'
})

// 获取位置类型标签
const getLocationTypeLabel = (type: string) => {
  const found = locationTypes.find(t => t.value === type)
  return found ? found.label : '未知'
}

const getCurrentLocation = (): Promise<GeolocationPosition> => {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('浏览器不支持地理位置功能'))
      return
    }

    navigator.geolocation.getCurrentPosition(
      (position) => resolve(position),
      (error) => reject(error),
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0
      }
    )
  })
}

const reverseGeocode = async (lat: number, lng: number) => {
  return new Promise<void>((resolve) => {
    if (!(window as any).BMap) {
      console.error('百度地图API未加载')
      return resolve()
    }

    const geoc = new (window as any).BMap.Geocoder()
    const point = new (window as any).BMap.Point(lng, lat)

    geoc.getLocation(point, (result: any) => {
      if (result) {
        currentLocation.value.address = result.address
        // 尝试从地址推断位置类型
        inferLocationType(result.address)
      }
      resolve()
    })
  })
}

// 根据地址推断位置类型
const inferLocationType = (address: string) => {
  const lowerAddr = address.toLowerCase()
  
  if (lowerAddr.includes('家') || lowerAddr.includes('住宅') || lowerAddr.includes('小区')) {
    selectedLocationType.value = 'home'
  } else if (lowerAddr.includes('公司') || lowerAddr.includes('办公') || lowerAddr.includes('商务')) {
    selectedLocationType.value = 'work'
  } else if (lowerAddr.includes('商场') || lowerAddr.includes('购物') || lowerAddr.includes('超市')) {
    selectedLocationType.value = 'shopping'
  } else if (lowerAddr.includes('机场') || lowerAddr.includes('车站') || lowerAddr.includes('地铁')) {
    selectedLocationType.value = 'transport'
  } else {
    selectedLocationType.value = 'other'
  }
  
  currentLocation.value.type = selectedLocationType.value
}

const fetchAndShowLocation = async () => {
  isLocating.value = true
  locationError.value = ''

  try {
    const position = await getCurrentLocation()
    currentLocation.value.coords = {
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      accuracy: position.coords.accuracy
    }

    await reverseGeocode(
      currentLocation.value.coords.latitude,
      currentLocation.value.coords.longitude
    )

    initialLocation.value = {
      lat: currentLocation.value.coords.latitude,
      lng: currentLocation.value.coords.longitude
    }
    console.log("获取的全部信息", currentLocation.value)
    // 打印完整位置信息到控制台
    console.log('获取到位置信息:', {
      time: new Date().toLocaleTimeString(),
      coordinates: {
        latitude: currentLocation.value.coords.latitude,
        longitude: currentLocation.value.coords.longitude
      },
      accuracy: currentLocation.value.coords.accuracy,
      address: currentLocation.value.address,
      type: currentLocation.value.type,
      typeLabel: getLocationTypeLabel(currentLocation.value.type)
    })
    const location_point = `${currentLocation.value.coords.longitude},${currentLocation.value.coords.latitude}`;
    // 发送位置信息到服务器
    updateUserTrack({
      recordTime: new Date().toLocaleTimeString(),
      locationPoint:location_point,
      accuracy: currentLocation.value.coords.accuracy,
      address: currentLocation.value.address,
      type: currentLocation.value.type,
      typeLabel: getLocationTypeLabel(currentLocation.value.type)
    })
    
  } catch (error) {
    console.error('获取位置失败:', error)
    locationError.value = error instanceof GeolocationPositionError
      ? getGeolocationErrorText(error.code)
      : String(error)
  } finally {
    isLocating.value = false
  }
}

const startTracking = () => {
  if (locationTimer.value) {
    clearInterval(locationTimer.value)
  }
  
  isTracking.value = true
  console.log('开始位置追踪,每20秒获取一次位置')
  
  // 立即获取一次位置
  fetchAndShowLocation()
  
  // 每20秒获取一次位置
  locationTimer.value = setInterval(async () => {
    console.log('定时获取位置...')
    await fetchAndShowLocation()
  }, trackingInterval)
}

const stopTracking = () => {
  if (locationTimer.value) {
    clearInterval(locationTimer.value)
    locationTimer.value = null
  }
  isTracking.value = false
  console.log('停止位置追踪')
}

const getGeolocationErrorText = (code: number) => {
  switch (code) {
    case GeolocationPositionError.PERMISSION_DENIED:
      return '用户拒绝了位置请求，请在浏览器设置中修改权限'
    case GeolocationPositionError.POSITION_UNAVAILABLE:
      return '无法获取位置信息，请检查GPS或网络连接'
    case GeolocationPositionError.TIMEOUT:
      return '获取位置超时，请重试'
    default:
      return '获取位置时发生未知错误'
  }
}

onUnmounted(() => {
  stopTracking()
})
</script>

<style scoped>
.location-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
}

.location-section {
  margin: 25px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.tracking-controls {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.location-type-selector {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.location-type-dropdown {
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background-color: white;
}

.tracking-button {
  padding: 8px 16px;
  background-color: #4a89dc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.tracking-button:hover {
  background-color: #3b7dd8;
}

.tracking-button.active {
  background-color: #f56c6c;
}

.tracking-button.active:hover {
  background-color: #f78989;
}

.tracking-status {
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.location-button {
  padding: 10px 20px;
  background-color: #4a89dc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 15px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
}

.location-button:hover {
  background-color: #3b7dd8;
}

.location-button:disabled {
  background-color: #a0b8e0;
  cursor: not-allowed;
}

.location-button i {
  margin-right: 8px;
  font-size: 16px;
}

.location-error {
  margin-top: 12px;
  padding: 10px;
  background-color: #ffebee;
  color: #f44336;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.location-error i {
  margin-right: 8px;
}

.location-info {
  margin-top: 15px;
  padding: 12px;
  background-color: #e8f5e9;
  border-radius: 4px;
  color: #2e7d32;
}

.location-info p {
  margin: 6px 0;
  display: flex;
  align-items: center;
}

.location-info i {
  margin-right: 8px;
  width: 16px;
  text-align: center;
}

.map-section {
  margin-top: 30px;
}

@media (max-width: 768px) {
  .location-container {
    padding: 15px;
  }

  .location-button {
    width: 100%;
    justify-content: center;
  }
  
  .tracking-controls {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .location-type-selector {
    width: 100%;
  }
  
  .location-type-dropdown {
    width: 100%;
  }
}
</style>